package com.lph.health.utils;

import com.lph.health.vo.MailVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.util.Arrays;

/**
 * 发送邮件工具类
 */
@Slf4j
@Component
public class MailUtil {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件
     * @param mailVo 发送内容
     * @return
     */
    public String sendMail(MailVo mailVo) {
        try {
            if (mailVo.isHtml()){
                // 创建邮件对象
                MimeMessage mimeMessage = mailSender.createMimeMessage();
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true); // 支持上传文件
                messageHelper.setFrom(from);
                messageHelper.setTo(mailVo.getReceivers());
                messageHelper.setSubject(mailVo.getSubject());
                messageHelper.setText(mailVo.getContent(), true);
                mailSender.send(mimeMessage);
                log.info("HTML邮件发送成功! 收件人-->{}", Arrays.asList(mailVo.getReceivers()));
            } else {
                // 创建邮件对象
                SimpleMailMessage mailMessage = new SimpleMailMessage();
                // 发件人
                mailMessage.setFrom(from);
                // 收件人
                mailMessage.setTo(mailVo.getReceivers());
                // 邮件主题
                mailMessage.setSubject(mailVo.getSubject());
                // 邮件内容
                mailMessage.setText(mailVo.getContent());

                // 发送
                mailSender.send(mailMessage);
                log.info("普通邮件发送成功收件人-->{}", Arrays.asList(mailVo.getReceivers()));
            }
            return "邮件发送成功!";
        } catch (Exception e){
            log.error("邮件发送失败--{}", e.getMessage());
            return "邮件发送失败";
        }
    }
}
